<?php

define('SERVER_ROOT', 'D:/my-apache/www');
define('SERVER', 'my-apache');
define('LOCAL_SOCKET', 'tcp://0.0.0.0');
define('PORT', '80');
define('VHOST_PATH', "D:/my-apache/vhost.xml");

/**
 * Function: get dir list
 *
 */
function getDir($dir) 
{
    $dirArray[] = NULL;
    if (false !=  ($handle = opendir ( $dir ))) {
        $i = 0;
        while ( false !== ($file = readdir ( $handle )) ) {
            //去掉"“.”、“..”以及带“.xxx”后缀的文件
            if ($file != "." && $file != ".." && !strpos($file,".")) {
                $dirArray[$i] = $file;
                $i++;
            }
        }
        closedir($handle);
    }
    return $dirArray;
}
 
/**
 * Function: get document list
 *
 */
function getFile($dir) 
{
    $fileArray[] = NULL;
    if (false != ($handle = opendir($dir))) {
        $i = 0;
        while ( false !== ($file = readdir($handle)) ) {
            //去掉"“.”、“..”以及带“.xxx”后缀的文件
            if ($file != "." && $file != ".." && strpos($file,".")) {
                $fileArray[$i] = $file;
                if($i == 100){
                    break;
                }
                $i++;
            }
        }
        closedir($handle);
    }
    return $fileArray;
}

/**
 * Function: mapping domain names to IP addresses
 * 
 */
function host($host) 
{
    $htmDoc = new DOMDocument;  
    $htmDoc->load(VHOST_PATH);  
  
    $list = $htmDoc->getElementsByTagName('host');  

    foreach ($list as $value) {
       	$hostName = $value->getElementsByTagName('hostName')->item(0)->nodeValue;

       	if ($hostName == $host) {
       		$documentRoot = $value->getElementsByTagName('documentRoot')->item(0)->nodeValue;
       		return $documentRoot;
       	}
	}   
	return 0;
}

/**
 * event handling
 * 
 */
function handleConn($conn) 
{
	echo "received request from ", stream_socket_get_name($conn, true), "\n";

	$line = trim(fgets($conn)); var_dump($line);
	echo "\r\n $line \r\n";
	list($method, $uri, $proto) = explode(' ', $line);

	/* 获取cookie和头信息 */	
	$_COOKIE = array();
	$headers = array();
	while ( ($line = fgets($conn)) != "\r\n" ) {
		$line = trim($line);

		$pos = strpos($line, ":");
		$headerName = substr($line, 0, $pos);
		$headerContent = substr($line, $pos + 2);
		$headers[$headerName] = $headerContent;

		if ($headerName == "Cookie") {
			$cookie = explode("; ", $headerContent);

			foreach ($cookie as $k) {
				list($cookieName, $cookieValue) = explode("=", $k);
				$_COOKIE[$cookieName] = $cookieValue;
			}
		}
	}
	print_r($headers);

 	/* 获取get参数和path */
	if (strpos($uri, '?')) {
		list($path, $param) = explode('?', $uri);

		$_GET = array();
		$param = explode('&', $param);
		foreach ($param as $key) {
			list($paramName, $paramValue) = explode('=', $key);
		
			$_GET[$paramName] = $paramValue;
		} 
	} else {
		$_GET = array();
		$path = $uri;
	}
	$path = SERVER_ROOT . $path;
	print_r($_GET);
	print_r($path);

	/* 查找域名映射 */
	$host = $headers['Host'];
//var_dump(host($host));
	$path = host($host)?host($host):$path;
	$path = str_replace("\\", "/", $path);
//var_dump($path);exit;
	/* *
	 * dir & document & 404
	 * get dir and documents list
	 */
	if (file_exists($path)) {

		if (is_dir($path)) {
			fwrite($conn, "$proto 200 ok\r\n");
	        fwrite($conn, "Server: " . SERVER . "\r\n");
	        fwrite($conn, "Content-Type: text/html\r\n");
	        fwrite($conn, "\r\n");

	        fwrite($conn, "<h1>$path</h1>\r\n");
	        fwrite($conn, "<a href='../'>..</a><br />");

			$dir = getDir($path);
			$hp = str_replace(SERVER_ROOT, "http://localhost", $path);
			foreach ($dir as $value) {
				
				fwrite($conn, "<a href='$hp$value'>" . $value . "</a><br />");
			}

			$file = getFile($path);
			foreach ($file as $value) {

				$index = strpos($value, "index");
				if ($index > -1) {

					$p = str_replace(SERVER_ROOT, "http://localhost/", $path);
					$u = $p . '/' . $value;
					
					fwrite($conn, "<script language='javascript' type='text/javascript'> window.location.href='$u';</script>");
				} else {
					fwrite($conn, "<a href='$hp/$value'>" . $value . "</a><br />");
				}
			}
		} else {
			/*  */
			fwrite($conn, "$proto 200 OK\r\n");
	        fwrite($conn, "Server: " . SERVER . "\r\n");
	        if (!isset($_COOKIE['PHPSESSID'])) {
	            fwrite($conn, "Set-Cookie: PHPSESSID=" . uniqid("myhttpd") . "\r\n");
	        }
	        fwrite($conn, "Content-Type: text/html\r\n");
	        fwrite($conn, "\r\n");

			/* 如果是文件，则执行 */
			ob_start();
			include("$path");
			$body = ob_get_contents();
			ob_end_clean();
			
			fwrite($conn, $body);
		}
	} else {
	/* 404页面 */
		fwrite($conn, "$proto 404 Not Found\r\n");
        fwrite($conn, "Server: " . SERVER . "\r\n");
        fwrite($conn, "Content-Type: text/html\r\n");
        fwrite($conn, "\r\n");

        fwrite($conn, "<h1>Not Found!</h1>");
        fwrite($conn, "<p>The requested URL $path was not found on this server.</p>");
        fwrite($conn, "<hr>");
        fwrite($conn, "<p>" . SERVER . "at port " . PORT . "</p>");
	}
}

$socket = stream_socket_server(LOCAL_SOCKET . ":" . PORT, $errno, $errstr);
if (!$socket) {
  echo "$errstr ($errno)<br />\n";
  exit();
}

while ($conn = stream_socket_accept($socket)) {
	stream_set_timeout($conn, 0);
	handleConn($conn);
	fclose($conn);
}


